Ext.namespace('App.ux');


/**
 * URL's for CRUD operations of data grid
 */
var proxy = new Ext.data.HttpProxy({
    api: {
        read : 'tablegrid/read',
        create : 'tablegrid/create',
        update: 'tablegrid/update',
        destroy: 'tablegrid/delete'
    }
});

/**
 * Dynamic Table Data Grid
 */
App.ux.DynamicGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
    initComponent: function(){
        var config = {
            viewConfig: {forceFit: true}, //columns have width re-proportioned at all times
            loadMask:true,
            store: new Ext.data.Store({
                proxy: proxy,
                reader: new Ext.data.JsonReader(),
                writer: new Ext.data.JsonWriter({
                    encode: true,
                    writeAllFields: false
                }),
                baseParams: {
                    databaseName: this.databaseName,
                    tableName: this.tableName
                },
                autoSave: false
            }),
            columns: []
        };
        Ext.apply(this, config);
        Ext.apply(this.initialConfig, config);
        this.tbar = this.buildTopToolbar(); // add the 'add', 'delete' and 'save' buttons
        this.relayEvents(this.store, ['destroy', 'save', 'update']);
        App.ux.DynamicGridPanel.superclass.initComponent.apply(this, arguments);
    },
    /**
     * buildTopToolbar
     */
    buildTopToolbar : function() {
        return [{
            text: 'Add',
            iconCls: 'silk-add',
            handler: this.onAdd,
            scope: this
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: this.onDelete,
            scope: this
        }, '-', {
            text: 'Save',
            iconCls: 'icon-save',
            handler: this.onSave,
            scope: this
        }];
    },
    onAdd: function() {
        var record = new this.store.recordType({});
        this.stopEditing();
        this.store.insert(0, record);
        this.startEditing(0, 1);
    },
    onSave: function(btn, ev) {
        this.store.save();
    },
    onDelete: function(btn, ev) {
        var index = this.getSelectionModel().getSelectedCell();
        if (!index) {
            return false;
        }
        var rec = this.store.getAt(index[0]);
        this.store.remove(rec);
        this.store.save();
    },
    onRender: function(ct, position){

        this.colModel.defaultSortable = true;
        App.ux.DynamicGridPanel.superclass.onRender.call(this, ct, position);
        /**
        * Grid is not masked for the first data load.
        * We are masking it while store is loading data
        */
        this.el.mask('Загрузка...');
        this.store.on('metachange', function(){
            if(typeof(this.store.reader.jsonData.columns) === 'object') {
                var columns = [];
                Ext.each(this.store.reader.jsonData.columns, function(column){
                    /**
                   * If column isn't primary key, then add editor
                   */
                    if ( !column.primary ) {
                        column.editor = new Ext.form.TextField({
                            allowBlank: false
                        });
                    }
                    columns.push(column); // Add column to ColumnModel
                });
                /**
                * Setting column model configuration
                */
                this.getColumnModel().setConfig(columns);
            }
            /**
            * Unmasking grid
            */
            this.el.unmask();
        }, this);
        /**
        * And finally load the data from server!
        */
        this.store.load();
    }
});